package com.doghome.testsecurity.config;

import com.doghome.testsecurity.dao.RoleMapper;
import com.doghome.testsecurity.pojo.Menu;
import com.doghome.testsecurity.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;

/**
 * 编写自定义投票器
 */
@Component
public class MyRoleVoter implements AccessDecisionVoter<FilterInvocation> {

    @Autowired
    private RoleMapper roleMapper;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean supports(ConfigAttribute attribute) {
        if (attribute.toString().equalsIgnoreCase("permitall")) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    public int vote(Authentication authentication, FilterInvocation object, Collection<ConfigAttribute> attributes) {
        if (authentication == null) {
            return ACCESS_DENIED;
        }
        int result = ACCESS_ABSTAIN;
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        String url = object.getRequestUrl();

        for (ConfigAttribute attribute : attributes) {
            if (this.supports(attribute)) {
                result = ACCESS_DENIED;

                // Attempt to find a matching granted authority
                for (GrantedAuthority authority : authorities) {
                    String roleName = authority.getAuthority();
                    Role role = roleMapper.selectByName(roleName);
                    for(Menu menu : role.getMenus()){
                        if(antPathMatcher.match(menu.getUrlPath(),url)){
                            return ACCESS_GRANTED;
                        }
                    }
                }
            }
        }

        return result;
    }


}
